#############################################
# 生产者, rocketmq-python 不支持windows
#############################################

from pprint import pprint
from rocketmq.client import Producer, Message
import json


class MQProducer():

    def getProducer(self,
                    groupId,  # group组
                    addr  # （服务器ip:port）
                    ):
        try:
            producer = Producer(groupId)
            producer.set_namesrv_addr(addr)  # rocketmq队列接口地址（服务器ip:port）
            producer.start()
            return producer
        except Exception as e:
            pprint('异常', e)
            return None

    def getBodyMsg(self, msg_body, topic, keys, tags):
        ss = json.dumps(msg_body).encode('utf-8')

        msg = Message(topic)  # topic名称
        msg.set_keys(keys)
        msg.set_tags(tags)
        msg.set_body(ss)  # message body
        return msg

    def send(self, groupId, addr, msg_body, topic, keys, tags):
        producer = self.getProducer(groupId, addr)
        try:
            msg = self.getBodyMsg(msg_body, topic, keys, tags)
            retmq = producer.send_sync(msg)
            pprint(retmq.status, retmq.msg_id, retmq.offset)
        except Exception as e:
            pprint('异常', e)
        finally:
            if producer:
                producer.shutdown()


if __name__ == '__main__':
    mq = MQProducer()
    groupId = 'GID_KANGMA_ORDER_CENTER_TEST_HW'
    addr = '47.114.62.187:9876'
    msg_body = '{"parms":[{"supplierId":44,"orderSn":"DD1347374517944717312","spreadStatus":0,"spreadDebitAmount":0,"buyUser":103,"spreadCreditAmount":40,"spreadAccountTime":1610075115646,"customerStoreId":80,"customerId":172,"orderPayTime":1610074093000}]}'
    topic = 'SPREAD_COMMISSION_INTO_DB_TEST_HW'
    keys = None
    tags = 'SPREAD_COMMISSION_INTO_DB_TEST_HW'
    mq.send(groupId, addr, msg_body, topic, keys, tags)
